import time
import threading

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

# Path to your ChromeDriver
CHROMEDRIVER_PATH = r"./chromedriver_mac137"


def perform_baidu_search(thread_name: str, search_term: str):
    print(f"Thread {thread_name}: Starting Baidu search for '{search_term}'")
    wd = None  # Initialize wd to None
    try:
        # Each thread gets its own WebDriver instance
        wd = webdriver.Chrome(service=Service(CHROMEDRIVER_PATH))
        wd.get("https://www.baidu.com")
        wd.implicitly_wait(10)

        element = wd.find_element(By.ID, "kw")
        # print(f"Thread {thread_name}: Search input HTML: {element.get_attribute('outerHTML')[:100]}...") # Optional: print part of HTML

        element.send_keys(search_term)
        time.sleep(1)  # Shorter sleep, adjust as needed

        # Simulate selecting a suggestion if necessary, or just search directly
        # For simplicity, let's assume direct search after typing
        # element.send_keys(Keys.ARROW_DOWN)
        # element.send_keys(Keys.ARROW_DOWN)
        # time.sleep(1)

        search_button = wd.find_element(By.ID, "su")
        search_button.click()

        # It's unusual to send Keys.ESCAPE to the search button after clicking.
        # If the goal was to close a suggestion box, it should be done on the input field.
        # For now, I'll keep it if it serves a specific purpose in your original flow.
        # If not needed, you can remove the next line.
        # search_button.send_keys(Keys.ESCAPE) # This might not have the intended effect on the button

        print(
            f"Thread {thread_name}: Search submitted for '{search_term}'. Current URL: {wd.current_url}"
        )
        time.sleep(13)  # Allow time for search results to load

    except Exception as e:
        print(f"Thread {thread_name}: An error occurred: {e}")
    finally:
        if wd:
            print(f"Thread {thread_name}: Closing browser.")
            wd.quit()
        print(f"Thread {thread_name}: Finished.")


if __name__ == "__main__":
    search_terms = ["今天热门", "Python Selenium"]

    threads = []

    start_time = time.time()

    for i, term in enumerate(search_terms):
        thread = threading.Thread(target=perform_baidu_search, args=(i, term))
        # thread = threading.Thread(
        #     target=perform_baidu_search, args=(f"Thread-{i+1}", term)
        # )
        threads.append(thread)
        thread.start()
        time.sleep(0.5)  # Stagger browser launches slightly if needed, can be removed

    for thread in threads:
        thread.join()  # Wait for all threads to complete

    end_time = time.time()
    print(f"All searches completed in {end_time - start_time:.2f} seconds.")
